<template>
  <ErrorNodata v-if="noUserError"></ErrorNodata>
  <Viewer v-else :router="viewerRouter"></Viewer>
</template>

<script setup>
import { defineAsyncComponent, onActivated, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import ErrorNodata from '@/components/common/ErrorNodata.vue'
import { useDesktopViewerRouter } from '@/compositions/viewer/router/desktopViewerRouter'
import API from '@/http'

const Viewer = defineAsyncComponent(() => import('@/components/viewer/Viewer.vue'))

const emits = defineEmits(['id'])

const viewerRouter = useDesktopViewerRouter('desktop-creator')
const { setFromCreator } = viewerRouter

const route = useRoute()

const noUserError = ref(false)

onMounted(active)
onActivated(active)

function active() {
  const { username } = route.params
  const { id, share_aff } = route.query

  // 有帶 query.id 的是從內部導過來的，直接拿來用
  if (id) {
    setFromCreator(parseInt(id))
  }
  // 沒有帶 query.id 的是使用者直接用連結進來的，只能先去跟後端查到 aff 後才能繼續下去
  else {
    API.Auth.detail({ data: { username, share_aff } }).then((d) => {
      if (d === null) {
        noUserError.value = true
      } else {
        setFromCreator(d.aff)
        emits('id', d.aff)
      }
    })
  }
}
</script>
